package cn.weakup.thread.question._volatile;

/**
 * @author Dawn
 * @version 1.0.0
 * @desc
 * @date 2022/5/14
 */
public class Test {
    private int a = 0;

    private volatile int b = 0;

    public static void main(String[] args) throws InterruptedException {
        Test test = new Test();
        /**
         * synchronized既能保证可见性，又能保证原子性
         */
        Thread threadA = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                synchronized (test){
                    test.a++;
                }
            }
            System.out.println("A执行完毕");
        });

        Thread threadB = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                synchronized (test){
                    test.a++;
                }
            }
            System.out.println("B执行完毕");
        });

        threadA.start();
        threadB.start();
        threadA.join();
        threadB.join();
        System.out.println(test.a);


        /**
         * volatile，只能保证可见性
         */
        Thread threadC = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                test.b++;
                if(test.b == 5000) {
                    System.out.println("C 已加到五千");
                }
            }
        });

        Thread threadD = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                if(test.b == 5000) {
                    System.out.println("D 已感知五千");
                }
            }
        });

        threadC.start();
        threadD.start();
        threadC.join();
        threadD.join();
        System.out.println(test.b);
    }
}
